import Vue from 'vue'
import router from '@router'
import Api from '@api'
import Store from '@store'
import Cookie from 'js-cookie'
router.beforeEach((to, from, next) => {
  const $vue = new Vue()
  let data = {
    token: $vue.getToken(),
    code: $vue.getValueFromUrl('code'),
    openId: Cookie.get('pay_openid')
  }
  let methods = {
    /**
     * @purpose 获取token
     */
    getToken (next) {
      let auto = setTimeout(() => {
        $vue.showLoading()
      }, 2000)
      Api.sign
        .token('', data.token)
        .then(r => {
          $vue.closeLoading()
          clearTimeout(auto)
          if (typeof r.data.status !== 'undefined' && r.data.status === 10000) {
            $vue.setToken(r.data.token)
            Store.dispatch('getUserInfo', (r) => {
              next({replace: true})
            })
          } else {
            $vue.removeToken()
            next()
          }
        })
    }
  }
  if (from.path === '/') {
    if (!$vue.isWeChat()) {
      window.location.replace('http://h5.enjoychina.cc' + window.location.pathname + window.location.search)
    } else {
      if (!data.openId) {
        if (data.code) {
          Api
            .sign
            .getNowWeChat(data.code)
            .then(r => {
              if (data.token) {
                methods.getToken(next)
              } else {
                window.location.href = window.location.protocol + '//' + window.location.host + window.location.pathname
              }
            })
        } else {
          Api
            .wechat
            .appid()
            .then(appid => {
              let callbackUrl = window.location.href
              let redirectUri = callbackUrl
              let authUri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${$vue.urlencode(redirectUri)}&response_type=code&scope=snsapi_base&state=${callbackUrl}`
              window.location.href = authUri
            })
        }
      } else {
        if (data.token) {
          methods.getToken(next)
        } else {
          next()
        }
      }
    }
  } else {
    next()
  }
})
